<?php
/**
  * The Class for the controller component of the application
  *
  */

class IndexController extends Zend_Controller_Action
{
    /**
     * The class constructor for the derived class
     *
     */

    private $_registry;
    private $_db;
    private $_user = null;
    private $_redirector;

    function init()
    {
        //Initiate the registry object
        $this->_registry = Zend_Registry::getInstance();
        $this->_db = $this->_registry->get('db');
        $this->_redirector = $this->_helper->getHelper('Redirector');

        $session = new Zend_Session_Namespace('User');
		if( isset($session->user) )
		{
			//Get an upto date record of the current user
			$Users = new Users();
			$this->_user = $Users->getUserById($session->user->uid);

			$this->_registry->user = $this->_user;		
			Ebay_Client::setUid($this->_user->uid);
		}
		else
		{
			$this->_user = null;
		}
		
		/*
		 * Check to see if the user has authenticated with the servers
		 * and also whether the user is on a login page already
		 */

        if (!$this->_user && $this->getRequest()->getParam('action') != 'login')
        {
           // Redirect the user to the login page
           $this->_redirector->gotoRoute(array('action' => 'login'), 'index');
        }
		
		// Create a record in the registry for global access to fresh user goodness, whether null or useful

        $this->view->headLink( array('rel' => 'favicon', 'href' => $this->view->baseUrl().'/img/favicon.ico') )
        ->appendStylesheet($this->view->baseUrl().'/css/main.css');
    }

    function indexAction()
    {
		// Setup the view helpers for javascript and css
        $this->view->headScript()->appendFile($this->view->baseUrl().'/js/prototype.js')
                                 ->appendFile($this->view->baseUrl().'/js/scriptaculous.js')
								 ->appendFile($this->view->baseUrl().'/js/date.js');
								 
        $this->pageTitle = 'Ebay Application';
		
		$ebay = new Ebay_Client();
		
		//Sync the user if they've just logged on
		$ebay->sync(null, true);
		
        $Items = new Items();

        $this->view->listings = $Items->getItems($this->_user->uid, true);
    }

	function createinvoiceAction()
	{
		$data = $this->_request->getPost('json', 'false');
        $data = Zend_Json::decode($data);
		
		if(!$data || !is_array($data['listings']))
		{
			$this->view->data = false;
			return $this->render();
		}
		
		$Items = new Items();
		$Transactions = new Transactions();
		$Buyers = new Buyers();
		
		$invoices = array();
		foreach($data['listings'] as $id)
		{
			if(!Zend_Validate::is($id, 'Int'))
			{
				continue;			
			}
			$item = $Items->getItem($id);
			if($item['status'] < 4)
			{
				continue;
			}
			
			$transaction = $Transactions->getByEbayId($item['ebayId']);
			$buyer = $Buyers->getByEbayUid($transaction->ebayUid);
			
			$item = array('title' => $item['title']);
			
			$invoices[] = array('transaction' => $transaction->toArray(), 'buyer' => $buyer->toArray(), 'item' => $item);			
		}
		if(sizeof($invoices) > 0)
		{

			$this->view->data = $invoices;
		}
		else
		{
			$this->view->data = false;
		}
	}
	
	function createpostageAction()
	{
		$data = $this->_request->getPost('json', 'false');
        $data = Zend_Json::decode($data);
		
		if(!$data || !is_array($data['listings']))
		{
			$this->view->data = false;
			return $this->render();
		}
		
		$Items = new Items();
		$Transactions = new Transactions();
		$Buyers = new Buyers();
		
		$addresses = array();
		foreach($data['listings'] as $id)
		{
			if(!Zend_Validate::is($id, 'Int'))
			{
				continue;			
			}
			$item = $Items->getItem($id);
			if($item['status'] < 4)
			{
				continue;
			}
			
			$transaction = $Transactions->getByEbayId($item['ebayId']);
			$buyer = $Buyers->getByEbayUid($transaction->ebayUid);
			
			$addresses[] = $buyer->toArray();			
		}
		if(sizeof($addresses) > 0)
		{
			$this->view->data = $addresses;
		}
		else
		{
			$this->view->data = false;
		}
	}
	
    function uploadimagesAction()
    {
        $counter = 0;
        $error = array();
        $newImages = array();
        $session = new Zend_Session_Namespace('Listing');
        $file = &$_FILES["image"];

        for($i = 0; $i < sizeof($file['name']); $i++)
        {
            $fname = $file["name"][$i];

            if($fname == "")
            {
                continue;
            }

            $ftype = $file["type"][$i];

            if(($ftype == "image/gif" ||
                $ftype == "image/jpeg" ||
                $ftype == "image/png" ||
                $ftype == "image/pjpeg") &&
                $file["size"][$i] < 2500000)
            {
                if ($file["error"][$i] > 0)
                {
                    $error[] ="Return Code: " . $file["error"][$i] . "<br />";
                    continue;
                }
                else
                {

                    if (file_exists(getcwd()."/host/" . $fname))
                    {
                        $error[] = $fname . " already exists. ";
                        continue;
                    }
                    else
                    {
                        // Move the temporary stored image file to the public directory
                        move_uploaded_file($file["tmp_name"][$i],
                        getcwd()."/host/tmp/" . $fname);

                        $images = $session->images;
                        $newImages[] = array('filename' => 'tmp/'.$fname);
                        $images[] = array('filename' => $fname);
                        $session->images = $images;
                    }
                }
            }
            else
            {
            $error[] = $fname." is invalid";
            continue;
            }
        }
        $this->_helper->layout->disableLayout();
        if(sizeof($newImages) > 0)
        {
            $this->view->data = array('status' => true, 'images' => $newImages);
        }
        else
        {
            $this->view->data = array('status' => false);
        }

    }

	function settingsAction()
	{
		if ($this->_request->isPost())
		{
			// Sync the users details from the server
			$submit = $this->_request->getPost('submit', false);
			if($submit && $submit == 'Sync')
			{
				
				$ebay = new Ebay_Client();
				$response = $ebay->getUser();
				
				$this->_user->data = unserialize($this->_user->data);		
var_dump($this->_user->data);
				// Create a reference to the address part
				$address = &$response->RegistrationAddress;
				
				$this->_user->data->email = (string) $response->Email;
				$this->_user->data->postcode = (string) $address->PostalCode;
				$this->_user->data->telephone = (string) $address->Phone;
				$this->_user->data->address = $address->Name . "\n" . $address->street . "\n" . $address->CityName . "\n" . 
											  $address->StateOrProvince . "\n" . $address->PostalCode;
				$this->_user->data = serialize($this->_user->data);	
				$this->_user->save();
				
				$this->view->user = $this->_user;
			}
		}
		else
		{
			$this->view->user = $this->_user;
		}
	}
	
    function saveImage($fname)
    {


    }
    function loginAction()
    {

        //Check if the user has already logged in and if so redirect them appropriately
        if($this->_user)
        {
            return $this->_redirector->goto(array('action' => 'index'));
        }

        if ($this->_request->isPost()) {
            $username = $this->_request->getParam('username', false);
            $password = $this->_request->getParam('password', false);
            $this->view->messages = array();
            if(!$username)
            {
                $this->view->messages[] = 'Please enter a username';
                $error = true;
            }

            if(!$password)
            {
                $this->view->messages[] = 'Please enter a password';
                $error = true;
            }

            if(isset($error))
            {
                return $this->render();
            }


            // Set up the Authadapter that plugs into Zend_Auth
            $authAdapter = new Zend_Auth_Adapter_DbTable($this->_db);

            $authAdapter->setTableName('users')
                        ->setIdentityColumn('username')
                        ->setCredentialColumn('password')
                        ->setCredentialTreatment('MD5(?)') //The Password is crosschecked using the MD5 hash checksum
                        ->setIdentity($username)
                        ->setCredential($password);

            //Get a Zend_Auth instance for processing session handling
            $auth = Zend_Auth::getInstance();
            $result = $auth->authenticate($authAdapter);

            if (!$result->isValid()) {
                // Litigate the error messages for the failed login proceedure
                switch ($result->getCode()) {
                    case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
                        $this->view->messages[] = "Your username was not recognised within our database.";
                        break;

                    case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
                        $this->view->messages[] = "The username and password are incorrect please try again.";
                        break;

                    default:
                        $this->view->messages[] = "The login attempt failed. Please try again.";
                        break;
                }

                return $this->render();

	        } else {
	            // Store the user details into the Session Storage
                $namespace = new Zend_Session_Namespace('User');
                $namespace->user = $authAdapter->getResultRowObject();
                $this->_redirector->gotoRoute(array('action' => 'index'), 'index');
	        }
		}
    }
    function storecategoriesAction()
    {
        $Config = new Config();
        $Categories = new Categories(); //Create a new Category models
        $ebay = new Ebay_Client();
        $select = $Config->select()->where('name = ?', "catVersion");
        $version = $Config->fetchRow($select);

        foreach($Categories->fetchAll() as $row)
        {
            $row->delete();
        }

        $categories = array();
        set_time_limit(120);
        $data = $ebay->getCategories();

        foreach($data->CategoryArray->Category as $category)
        {
            $Categories->insert(array('cid' => (string) $category->CategoryID,
                                'name' => (string) $category->CategoryName,
                                'pid' => (string) $category->CategoryParentID,
                                'level' => (string) $category->CategoryLevel
                                ));
        }
        $version->value = $data->CategoryVersion;
    }

    function updatecategoriesAction()
    {
        //Get the category version
        $Config = new Config();
        $ebay = new Ebay_Client();
        $select = $Config->select()->where('name = ?', "catVersion");
        $version = $Config->fetchRow($select);
        $ebayVersion = $ebay->getCategoryVersion();
        if($ebayVersion != $version->value)
        {
            //Get the new copy of the category hierarchy from EBAY and store locally

            $data = $ebay->getCategoryMappings($version->value);
            $rows = 0;

            $Categories = new Categories();

            foreach($data->CategoryMapping as $map)
            {
                $attr = $map->attributes();
                $where = $Categories->getAdapter()->quoteInto('cid = ?', $attr['oldID']);

                $rows += $Categories->update(array('cid' => $attr['id']), $where);
                print($where);
            }

            $version->value = $ebayVersion;
        }

    }

    function logoutAction()
    {
        //Create the Zend_Session_Namespace for accessing the Session stored
        Zend_Session::destroy();

        //Redirect the user to the login screen
       $this->_redirector->gotoRoute(array('action' => 'login'), 'index');
    }
}